package tsif.tcluster.session;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import tsif.tcluster.TClusterContext;

/**
 * 会话连接管理器<br>
 * 
 */
public class TClusterSessions {
	protected TClusterContext context; // 环境

	protected ConcurrentMap<Integer, TClusterSession> sessions; // 其他节点连接表

	public TClusterSessions(TClusterContext context) {
		this.context = context;

		sessions = new ConcurrentHashMap<>();
	}

	/** 添加连接 **/
	public TClusterSession tryToAddSession(int contextId, TClusterSession session) {
		// check
		if (session == null) {
			throw new RuntimeException("get session error! contextId=" + contextId);
		}

		// put session
		TClusterSession old = sessions.putIfAbsent(contextId, session);
		if (old != null) {
			session.close();
			session = old;
		}
		return session;
	}

	/** 获取或者创建远程session **/
	public TClusterSession get(int contextId) {
		return sessions.get(contextId);
	}

	/** 断开连接 **/
	public void remove(int id) {
		TClusterSession remove = this.sessions.remove(id);
		if (remove == null) {
			return; // is remove
		}
		remove.close();
		// System.out.println("remove session : " + id);
	}

	/** 移除所有连接 **/
	public void removeAll() {
		// remove session
		List<Integer> sessionIds = new ArrayList<>(this.sessions.keySet());
		for (Integer sessionId : sessionIds) {
			remove(sessionId);
		}
	}

	/** 更新session(超时关闭) **/
	public void update() {
		if (this.sessions.isEmpty()) {
			return;
		}

		// check session
		List<Integer> removeIds = new ArrayList<>();
		for (Map.Entry<Integer, TClusterSession> entry : sessions.entrySet()) {
			TClusterSession session = entry.getValue();
			if (session.alive()) {
				continue;
			}
			removeIds.add(entry.getKey());
		}

		// check remove
		if (removeIds.isEmpty()) {
			return;
		}
		// do remove
		for (Integer id : removeIds) {
			this.remove(id);
		}

	}

}
